//
//  DishThumbView.m
//  XRmenu
//
//  Created by loufq on 11-3-21.
//  Copyright 2011 E0571. All rights reserved.
//

#import "DishThumbView.h"
#import "DishThumbWrapperView.h"
#import "Product.h"
#import "XRmenuHelper.h"

@implementation DishThumbView
@synthesize delegate;
@synthesize item;
@synthesize wrapper;
@synthesize dishImageView;
@synthesize btnNewOrder;
@synthesize btnChangeOrder; 
@synthesize lblGoodsName;
@synthesize lblPrice;
@synthesize flipView;
@synthesize sendFlag;

CGFloat lastScaleFactor = 1;
#define kTagWrapperW (208)
#define kTagWrapperH (156)
#define kTagPaddingV (2)
#define kTapScale (1.1f)
#define kTapNoScale (1.0f)
#define kTagOperView 1000
#define kAnimationTimeNewTime 1.0f
#define kAnimationTimePlusTime 1.0f
#define kAnimationTimeMiunsTime 1.0f

#define kTagFilpView 401
//=========================================================== 
// dealloc
//=========================================================== 
- (void)dealloc
{
	self.flipView = nil;
	 delegate = nil;
	[item release];
    item = nil;
    [wrapper release];
    wrapper = nil;
    [dishImageView release];
    dishImageView = nil;
    [btnNewOrder release];
    btnNewOrder = nil;
    [btnChangeOrder release];
    btnChangeOrder = nil; 
    [lblGoodsName release];
    lblGoodsName = nil;
    [lblPrice release];
    lblPrice = nil;
    [super dealloc];
}

//初始化内容
-(id)initWithFrame:(CGRect)frame
{
	if ((self=[super initWithFrame:frame])) {
		
		
		//通知接收---删除 减少到
		
		CGSize vSize =frame.size;
		CGSize sSize =CGSizeMake(208,156);
		CGPoint sPosition =CGPointMake((vSize.width - sSize.width)/2, kTagPaddingV);
		CGRect scrollFrame =CGRectMake(1, 11, sSize.width, sSize.height); 
		UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];   
		self.wrapper = scrollView;
		self.wrapper.layer.borderWidth =1.0;
		self.wrapper.layer.borderColor= [UIColor grayColor].CGColor;
		[self addSubview:self.wrapper]; 
		CGRect dishFrame =CGRectMake(0, 0, sSize.width, sSize.height); 
		self.dishImageView = [[[UIImageView alloc] initWithFrame:dishFrame] autorelease];  
		self.dishImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
		[self.wrapper addSubview:self.dishImageView];
		[scrollView release];
		
		//文本行开始高度
		NSInteger iTop = sPosition.y + sSize.height + 20;
		
		//btn-新增加
		CGRect btnNewFrame =CGRectMake(-10, iTop, 35, 20); 
		self.btnNewOrder =[UIButton buttonWithType:UIButtonTypeCustom];
		self.btnNewOrder.frame=btnNewFrame;
		NSString* rPath = @"View/Album View/dish_new_unchecked.png";
		UIImage *recommendImg = [UIImage imageWithContentsOfFile:[XRmenuPublic getGeneralSkinImg:rPath]];
		[self.btnNewOrder setImage:recommendImg forState:UIControlStateNormal];
		[self addSubview:self.btnNewOrder];
		
		//菜名
		CGRect lblNameFrame =CGRectMake(17, iTop + 3, 120, 16); 
		UILabel* lbl = [[UILabel alloc] initWithFrame:lblNameFrame];
		self.lblGoodsName = lbl;
		[self.lblGoodsName setFont:[UIFont fontWithName:@"Arial" size:14]];
		[self.lblGoodsName setTextColor:[UIColor whiteColor]];  
		//[self attach1fingerTap:self.lblGoodsName sel:@selector(btnNewOrderTapped:)];
		UITapGestureRecognizer *tapGesture =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(btnNewOrderTapped:)]; 
        tapGesture.numberOfTapsRequired = 1;
        [self.lblGoodsName addGestureRecognizer:tapGesture];
        [tapGesture release]; 
		
		[self addSubview:self.lblGoodsName]; 
		[lbl release];
		
		//价格
		CGRect lblPriceFrame =CGRectMake(kTagWrapperW-100, iTop+3, 100, 16); 
		lbl =[[UILabel alloc] initWithFrame:lblPriceFrame];
		[lbl setFont:[UIFont fontWithName:@"Arial" size:16]];
		[lbl setTextColor:[UIColor grayColor]]; 
		lbl.textAlignment = UITextAlignmentRight;
		lbl.text=@"$P";
		self.lblPrice=lbl;
		[self addSubview:lbl];
		[lbl release];

		//调整份数 
		rPath = @"View/Album View/dish_count_bg.png";
		UIImage *adjustImg = [UIImage imageWithContentsOfFile:[XRmenuPublic getGeneralSkinImg:rPath]];
		CGRect btnChangeCountFrame =CGRectMake(kTagWrapperW-26, 0, 36, 22); 

		self.btnChangeOrder =[[[UIButton alloc] init] autorelease];
		self.btnChangeOrder.layer.contents = (id)adjustImg.CGImage;
		self.btnChangeOrder.layer.position = self.btnChangeOrder.center;
		self.btnChangeOrder.frame=btnChangeCountFrame;
		[self.btnChangeOrder setTitle:@"  " forState:UIControlStateNormal];
		[self.btnChangeOrder setTitle:@"  " forState:UIControlStateSelected];
		[self.btnChangeOrder setTitle:@"  " forState:UIControlStateDisabled];
		[self.btnChangeOrder setTitle:@"  " forState:UIControlStateHighlighted];
		
		[self.btnChangeOrder addTarget:self action:@selector(btnChangeOrderTapped:) 
					  forControlEvents:UIControlEventTouchUpInside];
		[self.btnChangeOrder setHidden:YES];
		[self addSubview:self.btnChangeOrder];
		
		//---单击事件---
		[self setExclusiveTouch:YES];
		
		//手势事件  
        tapGesture =
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(handleTapFrom:)]; 
        tapGesture.numberOfTapsRequired = 1;
        [self.wrapper addGestureRecognizer:tapGesture];
        [tapGesture release]; 
		UIPinchGestureRecognizer *pinchGesture =
        [[UIPinchGestureRecognizer alloc] initWithTarget:self
												  action:@selector(handlePinchGesture:)];  
		[self.wrapper addGestureRecognizer:pinchGesture]; 
		[pinchGesture release];
		
		//单击 ->到大图
		
		
		//上下到 切换
			UISwipeGestureRecognizer *recognizer1;
			recognizer1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeUp:)];
			recognizer1.direction = UISwipeGestureRecognizerDirectionUp;
			[self.wrapper addGestureRecognizer:recognizer1];
			[recognizer1 release];
			
			UISwipeGestureRecognizer *recognizer2;
			
			recognizer2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeDown:)];
			recognizer2.direction = UISwipeGestureRecognizerDirectionDown;
			[self.wrapper addGestureRecognizer:recognizer2];
			[recognizer2 release];
			

		
		
#ifdef DishTestColor 
		self.wrapper.backgroundColor = [UIColor lightGrayColor];
		self.lblPrice.backgroundColor =[UIColor yellowColor];
		self.lblGoodsName.backgroundColor =[UIColor purpleColor];
#else
		self.lblPrice.backgroundColor =[UIColor clearColor];
		self.lblGoodsName.backgroundColor =[UIColor clearColor];
		self.wrapper.backgroundColor = [UIColor clearColor];
#endif

		//是否推荐--
		
		rPath =[NSString stringWithFormat:@"View/Album View/%@/dish_recommand.png",APPSESSION.language];
		recommendImg = getSkinImg(rPath);
		CALayer *recommandLayer = [CALayer layer];
		recommandLayer.name = @"recommand";
		recommandLayer.bounds = CGRectMake(0,0, 20.f, 20.f); 
		recommandLayer.cornerRadius = 1;
		recommandLayer.position = CGPointMake(self.wrapper.frame.size.width-23/2, self.wrapper.frame.size.height-23/2);
		recommandLayer.contents = (id)recommendImg.CGImage;
		//recommandLayer.contents = (id)getSkinImg(loc(@"View/Album View/dish_recommand.png")).CGImage;
		recommandLayer.hidden =YES;
		[self.wrapper.layer addSublayer:recommandLayer]; 
	 
		btnNewFrame =CGRectMake(0, iTop, 150, 20); 
		UIButton* btn =[UIButton buttonWithType:UIButtonTypeCustom];
		btn.frame=btnNewFrame;
		//[btn setBackgroundColor:[UIColor redColor]];
		[btn addTarget:self action:@selector(btnNewOrderTapped:) 
					  forControlEvents:UIControlEventTouchUpInside];
		[self addSubview:btn]; 
		
	}
	return self;
}

-(void)setDislpayMode:(NSInteger)aDisplayMode
{
	return;
	displayMode = aDisplayMode;
 
	switch (displayMode) {
		case DisplayModelWithShow://仅仅显示基本信息用
			self.btnNewOrder.hidden=YES;
			self.btnChangeOrder.hidden =YES;
			break;
		case DisplayModelWithSimple://显示加跳转到大图用
			self.btnNewOrder.hidden=YES;
			self.btnChangeOrder.hidden =YES;
			break;
		case DisplayModelWithAll://全部功能
			self.btnNewOrder.hidden=NO;
			self.btnChangeOrder.hidden =NO; 
			//是否推荐
						
			break;
		default:
			break;
	} 
}

//显示内容
-(void)showWithItem:(id)aItem
{  

	//设置内容
	self.item = (Product*) aItem;
	
	[self setDislpayMode:displayMode];  
 
	DebugLog(@"类型：：%d",[item.pType intValue]);
 
	XRmenuError* error =nil; 
	//下是菜名
	self.lblGoodsName.text = JsonFiled(item.pName);// [NSString stringWithFormat:@"%@",item.pName];
	//显示价格
	float fPrice =[self.item.pSalePrice floatValue];
	
	self.lblPrice.text = [NSString stringWithFormat:@"%@ %0.2f/%@",[APPSESSION.allconfig getStringValueAtPath:@"System Config/currency"],fPrice,JsonFiled(self.item.pUnit)];
	//显示图片 
	self.dishImageView.image = getAlbumImg(([NSString stringWithFormat:@"%@", self.item.pEntityId]) ,error);
	//是否推荐
	NSArray* layers = self.wrapper.layer.sublayers;
	 NSUInteger i, count = [layers count];
	 for (i = 0; i < count; i++) {
		 CALayer * obj = [layers objectAtIndex:i];
		 if ([obj.name isEqualToString:@"recommand"]) {
			 obj.hidden = ![item.pIsRecommend boolValue];
			 if (!obj.hidden) {
				// obj.contents = (id)getSkinImg(loc(@"View/Album View/dish_recommand.png")).CGImage;
			 }
		 }
	}
	DebugLog(@"%@---%d--%d",item.pName,[XRmenuPublic getProductNum:item],[XRmenuPublic getOrderedNum]);	
	//已点份数
	if ([XRmenuPublic getProductNum:item]!=0) {
		[self.btnChangeOrder setTitle:[NSString stringWithFormat:@"%d",	[XRmenuPublic getProductNum:item]] forState:UIControlStateNormal];
		self.btnChangeOrder.hidden =NO;
		self.btnNewOrder.transform = CGAffineTransformMakeScale(0.9f, 0.9f);
	}
	else {
		self.btnChangeOrder.hidden =YES; 
		self.btnNewOrder.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
	}
	DebugLog(@"4");	
}
 
-(void)jumpToPhoto:(id)sender
{
	[[self viewWithTag:kTagFilpView] removeFromSuperview];
	postNWithObj(kMessage_Dish_AlbumToPhoto,self.item.pProductId);
}

-(void)flipHack2
{
	CGSize sSize =CGSizeMake(208,156);
	CGRect scrollFrame =CGRectMake(0, 0, sSize.width, sSize.height); 
	DishThumbFlipView* fp =[[DishThumbFlipView alloc] initWithThumbView:self];
	fp.backgroundColor = [UIColor blackColor];
	fp.frame = scrollFrame;
	fp.tag = kTagFilpView; 
	//手势事件  
	UITapGestureRecognizer *tapGesture =
	[[UITapGestureRecognizer alloc] initWithTarget:self
											action:@selector(handleTapFrom:)]; 
	tapGesture.numberOfTapsRequired = 1;
	[fp addGestureRecognizer:tapGesture];
	[tapGesture release];  
	[self.wrapper addSubview:fp];
	[self bringSubviewToFront:self.btnChangeOrder];
	[fp release];
}
 
-(IBAction) handleSwipeDown:(UIGestureRecognizer *) sender{
	[[self.superview viewWithTag:kTagOperView] removeFromSuperview];
	
	//父亲类的所有同类都还原	
	if ([self.wrapper viewWithTag:kTagFilpView]) {
		//翻转其他的  
		CGPoint location = [sender locationInView:self.wrapper];
		DebugLog(@"%@",NSStringFromCGPoint(location));
		
		
		
		[[self viewWithTag:kTagFilpView] removeFromSuperview]; 
		[UIView beginAnimations:@"animationImg2" context:nil];
		[UIView setAnimationDuration:0.8f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		[UIView setAnimationRepeatAutoreverses:NO];
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.wrapper cache:YES];
		[UIView commitAnimations];  
	}
	else { 
		//正面-》反面
		
		NSArray* views = [self.superview subviews];
		NSUInteger i, count = [views count];
		for (i = 0; i < count; i++) {
			DishThumbView * obj = [views objectAtIndex:i];
			if ([obj isKindOfClass:[self class] ]) {
				if ([obj.wrapper viewWithTag:kTagFilpView ]) { 
					[[obj.wrapper viewWithTag:kTagFilpView ] removeFromSuperview];
				}
			}
		}
		
		[self flipHack2];
		[UIView beginAnimations:@"animationImg" context:nil];
		[UIView setAnimationDuration:0.8f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		[UIView setAnimationRepeatAutoreverses:NO];
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.wrapper cache:YES];
		[UIView commitAnimations];  
	}
}


-(IBAction) handleSwipeUp:(UIGestureRecognizer *) sender {
	
	[[self.superview viewWithTag:kTagOperView] removeFromSuperview];
	
	//父亲类的所有同类都还原	
	if ([self.wrapper viewWithTag:kTagFilpView]) {
		//翻转其他的  
		CGPoint location = [sender locationInView:self.wrapper];
		DebugLog(@"%@",NSStringFromCGPoint(location));
		 
		[[self viewWithTag:kTagFilpView] removeFromSuperview]; 
		[UIView beginAnimations:@"animationImg2" context:nil];
		[UIView setAnimationDuration:0.8f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		[UIView setAnimationRepeatAutoreverses:NO];
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.wrapper cache:YES];
		[UIView commitAnimations];  
	}
	else { 
		//正面-》反面
		
		NSArray* views = [self.superview subviews];
		NSUInteger i, count = [views count];
		for (i = 0; i < count; i++) {
			DishThumbView * obj = [views objectAtIndex:i];
			if ([obj isKindOfClass:[self class] ]) {
				if ([obj.wrapper viewWithTag:kTagFilpView ]) { 
					[[obj.wrapper viewWithTag:kTagFilpView ] removeFromSuperview];
				}
			}
		}
		
		[self flipHack2];
		[UIView beginAnimations:@"animationImg" context:nil];
		[UIView setAnimationDuration:0.8f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		[UIView setAnimationRepeatAutoreverses:NO];
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.wrapper cache:YES];
		[UIView commitAnimations];  
	}
	
	DebugLog(@"%f,%f,%f,%f,%f,%f",
			 self.wrapper.transform.a //1.200000
			 ,self.wrapper.transform.b
			 ,self.wrapper.transform.c
			 ,self.wrapper.transform.d//1.200000
			 ,self.wrapper.transform.tx
			 ,self.wrapper.transform.ty
			 );

}
//---handle tap gesture---
-(IBAction) handleTapFrom:(UIGestureRecognizer *) sender {
	CGPoint location = [sender locationInView:self.wrapper];
	//跳转到大图	
	if (CGRectContainsPoint(CGRectMake(154, 127, 204-154, 154-127), location)) {
		//[APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"View/A_Flips.mp3"]];
		//[self jumpToPhoto:nil];
		//转回到正面
		[[self viewWithTag:kTagFilpView] removeFromSuperview]; 
		[UIView beginAnimations:@"animationImg2" context:nil];
		[UIView setAnimationDuration:0.8f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		[UIView setAnimationRepeatAutoreverses:NO];
		[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.wrapper cache:YES];
		[UIView commitAnimations]; 
		return;
	}
	[self jumpToPhoto:nil];

}

//还原图片到原始大小
-(void)beforeScale
{
	[UIView beginAnimations:@"test" context:nil];
	[UIView setAnimationDuration:0.2];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
	self.wrapper.transform = CGAffineTransformMakeScale(1,1); 
	[UIView commitAnimations];
}
//---handle Pinch gesture---
-(IBAction) handlePinchGesture:(UIGestureRecognizer *) sender { 
 
	
	CGFloat factor = [(UIPinchGestureRecognizer *) sender scale];	
    if (factor > 1) {//放大
		
		if ([self.superview viewWithTag:kTagOperView]) {
			[[self.superview viewWithTag:kTagOperView] removeFromSuperview];
		}
		
		[self.superview bringSubviewToFront:self];
        self.wrapper.transform = CGAffineTransformMakeScale(lastScaleFactor + (factor-1),
															lastScaleFactor + (factor-1));
    } else {//缩小
        self.wrapper.transform = CGAffineTransformMakeScale(kTapNoScale,kTapNoScale);
    }
	
    //if (sender.state == UIGestureRecognizerStateEnded){//手势即将结束的一刻
#pragma mark todo 是否是菜类判断
		if (factor>1.2) {
			lastScaleFactor =1;
			self.wrapper.transform = CGAffineTransformMakeScale(kTapNoScale,kTapNoScale);
			if (self.item&&self.item.pProductId) {
				if (sendFlag) {
					return;
				}
				postNWithObj(kMessage_Dish_AlbumToPhoto,self.item.pProductId);
				[self performSelector:@selector(rePichOk:) withObject:nil afterDelay:1];
				
				sendFlag= YES;
			}
			return;
		}
		lastScaleFactor = factor>1? (lastScaleFactor + factor -1) : 1;
    //}  
}

-(void)rePichOk:(id)sender
{
	self.sendFlag = NO;
}

//增加一份新菜 
-(void)btnNewOrderTapped:(id)sender 
{
	
	DebugLog(@"%f",self.btnNewOrder.transform.a);
	
	if ([XRmenuPublic getProductNum:self.item] > 0) {
		//已经有点菜数
		return ;
	}
 
	[APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"View/A_ButtonClicked.mp3"]];
	[[self.superview viewWithTag:kTagOperView] removeFromSuperview];
#pragma mark todo 自己处理增加操作 成功后动画效果
	if (![XRmenuPublic insertNewOrder:self.item]) {
		//return;
	}
	
	postN(kMessage_TopBar_orderedChange);
	self.btnNewOrder.transform = CGAffineTransformMakeScale(0.9f, 0.9f);
	self.btnChangeOrder.hidden = NO;

	NSString* count =[NSString stringWithFormat:@"%d",[XRmenuPublic getProductNum:self.item]];
	[self.btnChangeOrder setTitle:count forState:UIControlStateNormal];
	[self.btnChangeOrder setTitle:count forState:UIControlStateSelected];
	[self.btnChangeOrder setTitle:count forState:UIControlStateDisabled];
	[self.btnChangeOrder setTitle:count forState:UIControlStateHighlighted];

	if (self.delegate) {
		[self.delegate dishThumbView:self addTapped:sender];
	}
}

//打开操作视图
-(void)btnChangeOrderTapped:(UIButton*)sender
{
	[APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"View/A_ButtonClicked.mp3"]];
	postNWithObj(kMessage_DishMain_SwitchTopBarFront,self);
	self.wrapper.transform = CGAffineTransformMakeScale(kTapNoScale,kTapNoScale); 
	if (self.delegate) {
		[self.delegate dishThumbView:self adjustTapped:sender];
	}	
}
-(void)resumeToOriState
{
	NSString* rPath = @"View/Album View/dish_new_unchecked.png";
	UIImage *recommendImg = getSkinImg(rPath);
	[self.btnNewOrder setImage:recommendImg forState:UIControlStateNormal];
	self.btnNewOrder.transform = CGAffineTransformMakeScale(1, 1);
	self.btnChangeOrder.hidden = YES;
}

-(void)changeLanguage:(NSNotification *)notification
{
	[[self viewWithTag:kTagFilpView] removeFromSuperview];
	
	self.lblGoodsName.text = JsonFiled(item.pName);
	float fPrice =[self.item.pSalePrice floatValue];
	self.lblPrice.text = [NSString stringWithFormat:@"%@ %0.2f/%@",[APPSESSION.allconfig getStringValueAtPath:@"System Config/currency"],fPrice,JsonFiled(self.item.pUnit)];
	//View/Album View/dish_recommand.png
	
	NSArray* layers = self.wrapper.layer.sublayers;
	NSUInteger i, count = [layers count];
	for (i = 0; i < count; i++) {
		CALayer * obj = [layers objectAtIndex:i];
		if ([obj.name isEqualToString:@"recommand"]) {
			[obj removeFromSuperlayer];
			NSString* rPath =[NSString stringWithFormat:@"View/Album View/%@/dish_recommand.png",APPSESSION.language];
			CALayer *recommandLayer = [CALayer layer];
			recommandLayer.name = @"recommand";
			recommandLayer.bounds = CGRectMake(0,0, 20.f, 20.f); 
			recommandLayer.cornerRadius = 1;
			recommandLayer.position = CGPointMake(self.wrapper.frame.size.width-23/2, self.wrapper.frame.size.height-23/2);
			recommandLayer.contents = (id)getSkinImg(rPath).CGImage;
			//recommandLayer.contents = (id)getSkinImg(loc(@"View/Album View/dish_recommand.png")).CGImage;
			recommandLayer.hidden =YES;
			[self.wrapper.layer addSublayer:recommandLayer]; 
		}
	}  
}


@end
